package com.study.javaFx.view;

import com.study.javaFx.model.Usage;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.math.BigDecimal;
import java.time.LocalDateTime;

public class UsageView {

    

    /**
     * 显示新增上机记录的窗口
     */
    public void showAddWindow() {
        Stage stage = new Stage();
        stage.setTitle("新增上机记录");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        // 机器ID下拉框
        grid.add(new Label("机器ID:"), 0, 0);
        ComboBox<Integer> machineIdCombo = new ComboBox<>();
        grid.add(machineIdCombo, 1, 0);

        // 用户ID下拉框
        grid.add(new Label("用户ID:"), 0, 1);
        ComboBox<Integer> userIdCombo = new ComboBox<>();
        grid.add(userIdCombo, 1, 1);

        // 员工ID下拉框
        grid.add(new Label("员工ID:"), 0, 2);
        ComboBox<Integer> staffIdCombo = new ComboBox<>();
        grid.add(staffIdCombo, 1, 2);

        // 异步加载机器ID
        java.net.http.HttpRequest machineReq = java.net.http.HttpRequest.newBuilder()
            .uri(java.net.URI.create("http://localhost:8080/api/machine/get"))
            .GET().build();
        java.net.http.HttpClient.newHttpClient().sendAsync(machineReq, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
            .thenApply(java.net.http.HttpResponse::body)
            .thenAccept(json -> {
                try {
                    com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                    com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                    com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                    java.util.List<Integer> ids = new java.util.ArrayList<>();
                    for (com.fasterxml.jackson.databind.JsonNode item : dataNode) {
                        ids.add(item.get("machineId").asInt());
                    }
                    javafx.application.Platform.runLater(() -> machineIdCombo.getItems().setAll(ids));
                } catch (Exception ex) {
                    javafx.application.Platform.runLater(() -> showAlert("加载机器ID失败: " + ex.getMessage(), false));
                }
            });

        // 异步加载用户ID
        java.net.http.HttpRequest userReq = java.net.http.HttpRequest.newBuilder()
            .uri(java.net.URI.create("http://localhost:8080/api/user/get"))
            .GET().build();
        java.net.http.HttpClient.newHttpClient().sendAsync(userReq, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
            .thenApply(java.net.http.HttpResponse::body)
            .thenAccept(json -> {
                try {
                    com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                    com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                    com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                    java.util.List<Integer> ids = new java.util.ArrayList<>();
                    for (com.fasterxml.jackson.databind.JsonNode item : dataNode) {
                        ids.add(item.get("userId").asInt());
                    }
                    javafx.application.Platform.runLater(() -> userIdCombo.getItems().setAll(ids));
                } catch (Exception ex) {
                    javafx.application.Platform.runLater(() -> showAlert("加载用户ID失败: " + ex.getMessage(), false));
                }
            });

        // 异步加载员工ID
        java.net.http.HttpRequest staffReq = java.net.http.HttpRequest.newBuilder()
            .uri(java.net.URI.create("http://localhost:8080/api/staff/get"))
            .GET().build();
        java.net.http.HttpClient.newHttpClient().sendAsync(staffReq, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
            .thenApply(java.net.http.HttpResponse::body)
            .thenAccept(json -> {
                try {
                    com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                    com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                    com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                    java.util.List<Integer> ids = new java.util.ArrayList<>();
                    for (com.fasterxml.jackson.databind.JsonNode item : dataNode) {
                        ids.add(item.get("staffId").asInt());
                    }
                    javafx.application.Platform.runLater(() -> staffIdCombo.getItems().setAll(ids));
                } catch (Exception ex) {
                    javafx.application.Platform.runLater(() -> showAlert("加载员工ID失败: " + ex.getMessage(), false));
                }
            });

        Button submitBtn = new Button("开始上机");
        submitBtn.setOnAction(e -> {
            Integer machineId = machineIdCombo.getValue();
            Integer userId = userIdCombo.getValue();
            Integer staffId = staffIdCombo.getValue();
            if (machineId == null || userId == null || staffId == null) {
                showAlert("请选择所有字段", false);
                return;
            }
            // 构造Usage对象，准备提交到后端
            com.study.javaFx.model.Usage usage = new com.study.javaFx.model.Usage();
            usage.setMachineId(machineId);
            usage.setUserId(userId);
            usage.setStaffId(staffId);
            usage.paymentStatusProperty().set("ongoing"); // 设置支付状态为ongoing
            try {
                com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                String json = objectMapper.writeValueAsString(usage);
                java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                        .uri(java.net.URI.create("http://localhost:8080/api/usage/add"))
                        .header("Content-Type", "application/json")
                        .POST(java.net.http.HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                java.net.http.HttpClient.newHttpClient().sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(java.net.http.HttpResponse::body)
                        .thenAccept(resp -> javafx.application.Platform.runLater(() -> {
                            showInfoDialog("上机成功！");
                            stage.close();
                        }))
                        .exceptionally(ex -> { javafx.application.Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage(), false)); return null; });
            } catch (Exception ex) {
                showAlert("序列化失败: " + ex.getMessage(), false);
            }
        });

        grid.add(submitBtn, 1, 4);
        Scene scene = new Scene(grid, 350, 250);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示修改上机记录的窗口 (如下机、结算)
     */
    public void showUpdateWindow() {
        Stage stage = new Stage();
        stage.setTitle("结束上机并结算");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("上机记录ID:"), 0, 0);
        ComboBox<Integer> usageIdCombo = new ComboBox<>();
        grid.add(usageIdCombo, 1, 0);

        // 异步加载endTime为null的usageId
        java.net.http.HttpRequest allReq = java.net.http.HttpRequest.newBuilder()
                .uri(java.net.URI.create("http://localhost:8080/api/usage/get"))
                .GET().build();
        java.net.http.HttpClient.newHttpClient().sendAsync(allReq, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(java.net.http.HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        java.util.List<Integer> ids = new java.util.ArrayList<>();
                        for (com.fasterxml.jackson.databind.JsonNode usage : dataNode) {
                            if (usage.get("endTime").isNull()) {
                                ids.add(usage.get("usageId").asInt());
                            }
                        }
                        javafx.application.Platform.runLater(() -> usageIdCombo.getItems().setAll(ids));
                    } catch (Exception ex) {
                        javafx.application.Platform.runLater(() -> showAlert("加载上机记录ID失败: " + ex.getMessage(), false));
                    }
                });

        Button submitBtn = new Button("下机结算");
        submitBtn.setOnAction(e -> {
            Integer usageId = usageIdCombo.getValue();
            if (usageId == null) {
                showAlert("请选择要结算的上机记录ID", false);
                return;
            }
            // 构造请求体，只需包含usageId，后端可自动补全endTime等
            com.study.javaFx.model.Usage usage = new com.study.javaFx.model.Usage();
            usage.setUsageId(usageId);
            try {
                com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                String json = objectMapper.writeValueAsString(usage);
                java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                        .uri(java.net.URI.create("http://localhost:8080/api/usage/update"))
                        .header("Content-Type", "application/json")
                        .PUT(java.net.http.HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                java.net.http.HttpClient.newHttpClient().sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(java.net.http.HttpResponse::body)
                        .thenAccept(resp -> javafx.application.Platform.runLater(() -> {
                            showInfoDialog("下机成功！");
                            stage.close();
                        }))
                        .exceptionally(ex -> { javafx.application.Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage(), false)); return null; });
            } catch (Exception ex) {
                showAlert("序列化失败: " + ex.getMessage(), false);
            }
        });
        
        grid.add(submitBtn, 1, 1);
        Scene scene = new Scene(grid, 350, 150);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 显示删除上机记录的窗口
     */
    public void showDeleteWindow() {
        Stage stage = new Stage();
        stage.setTitle("删除上机记录");

        GridPane grid = new GridPane();
        grid.setPadding(new Insets(20));
        grid.setVgap(10);
        grid.setHgap(10);

        grid.add(new Label("记录ID:"), 0, 0);
        ComboBox<Integer> idCombo = new ComboBox<>();
        grid.add(idCombo, 1, 0);

        Button submitBtn = new Button("删除");
        submitBtn.setDisable(true);

        // 异步加载所有可删除的usageId
        java.net.http.HttpRequest allReq = java.net.http.HttpRequest.newBuilder()
                .uri(java.net.URI.create("http://localhost:8080/api/usage/get"))
                .GET().build();
        java.net.http.HttpClient.newHttpClient().sendAsync(allReq, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(java.net.http.HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        java.util.List<Integer> ids = new java.util.ArrayList<>();
                        for (com.fasterxml.jackson.databind.JsonNode usage : dataNode) {
                            ids.add(usage.get("usageId").asInt());
                        }
                        javafx.application.Platform.runLater(() -> {
                            idCombo.getItems().setAll(ids);
                            if (!ids.isEmpty()) submitBtn.setDisable(false);
                        });
                    } catch (Exception ex) {
                        javafx.application.Platform.runLater(() -> showAlert("加载记录ID失败: " + ex.getMessage(), false));
                    }
                });

        submitBtn.setOnAction(e -> {
            Integer id = idCombo.getValue();
            if (id == null) {
                showAlert("请选择要删除的记录ID", false);
                return;
            }
            Usage usage = new Usage();
            usage.setUsageId(id);
            try {
                com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
                String json = objectMapper.writeValueAsString(usage);
                java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder()
                        .uri(java.net.URI.create("http://localhost:8080/api/usage/delete"))
                        .header("Content-Type", "application/json")
                        .method("DELETE", java.net.http.HttpRequest.BodyPublishers.ofString(json, java.nio.charset.StandardCharsets.UTF_8))
                        .build();
                java.net.http.HttpClient.newHttpClient().sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                        .thenApply(java.net.http.HttpResponse::body)
                        .thenAccept(resp -> javafx.application.Platform.runLater(() -> {
                            try {
                                com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(resp);
                                String code = node.has("code") ? node.get("code").asText() : "";
                                String info = node.has("info") ? node.get("info").asText() : "";
                                if ("0000".equals(code)) {
                                    showInfoDialog(info.isEmpty() ? "删除成功！" : info);
                                    stage.close();
                                } else {
                                    showInfoDialog(info.isEmpty() ? "删除失败！" : info);
                                }
                            } catch (Exception ex) {
                                showAlert("响应解析失败: " + ex.getMessage(), false);
                            }
                        }));
            } catch (Exception ex) {
                showAlert("序列化失败: " + ex.getMessage(), false);
            }
        });

        grid.add(submitBtn, 1, 1);
        Scene scene = new Scene(grid, 350, 150);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 弹窗方式显示查询上机记录界面，仿照MachineView实现
     */
    public void showQueryWindow() {
        Stage dialog = new Stage();
        dialog.setTitle("查询上机记录");
        dialog.initModality(javafx.stage.Modality.APPLICATION_MODAL);

        TableView<com.study.javaFx.model.Usage> table = new TableView<>();
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        TableColumn<com.study.javaFx.model.Usage, Number> usageIdCol = new TableColumn<>("记录ID");
        usageIdCol.setCellValueFactory(cellData -> cellData.getValue().usageIdProperty());
        TableColumn<com.study.javaFx.model.Usage, Number> machineIdCol = new TableColumn<>("机器ID");
        machineIdCol.setCellValueFactory(cellData -> cellData.getValue().machineIdProperty());
        TableColumn<com.study.javaFx.model.Usage, Number> userIdCol = new TableColumn<>("用户ID");
        userIdCol.setCellValueFactory(cellData -> cellData.getValue().userIdProperty());
        TableColumn<com.study.javaFx.model.Usage, Number> staffIdCol = new TableColumn<>("员工ID");
        staffIdCol.setCellValueFactory(cellData -> cellData.getValue().staffIdProperty());
        TableColumn<com.study.javaFx.model.Usage, String> startTimeCol = new TableColumn<>("开始时间");
        startTimeCol.setCellValueFactory(cellData -> cellData.getValue().startTimeProperty());
        TableColumn<com.study.javaFx.model.Usage, String> endTimeCol = new TableColumn<>("结束时间");
        endTimeCol.setCellValueFactory(cellData -> cellData.getValue().endTimeProperty());
        TableColumn<com.study.javaFx.model.Usage, Number> durationCol = new TableColumn<>("时长(分钟)");
        durationCol.setCellValueFactory(cellData -> cellData.getValue().durationProperty());
        TableColumn<com.study.javaFx.model.Usage, String> costCol = new TableColumn<>("费用");
        costCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(cellData.getValue().getCost().toString()));
        TableColumn<com.study.javaFx.model.Usage, String> paymentStatusCol = new TableColumn<>("支付状态");
        paymentStatusCol.setCellValueFactory(cellData -> cellData.getValue().paymentStatusProperty());
        table.getColumns().addAll(usageIdCol, machineIdCol, userIdCol, staffIdCol, startTimeCol, endTimeCol, durationCol, costCol, paymentStatusCol);

        // 查询面板
        GridPane queryPane = new GridPane();
        queryPane.setPadding(new Insets(10));
        queryPane.setHgap(10);
        queryPane.setVgap(10);
        queryPane.add(new Label("输入记录ID:"), 0, 0);
        TextField idField = new TextField();
        queryPane.add(idField, 1, 0);
        Button queryBtn = new Button("查询");
        queryPane.add(queryBtn, 2, 0);

        // 定义后端基础URL、httpClient和objectMapper
        String BASE_URL = "http://localhost:8080/api/usage";
        java.net.http.HttpClient httpClient = java.net.http.HttpClient.newHttpClient();
        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();

        // 初始加载全部上机记录数据
        System.out.println("请求全部上机记录数据: " + BASE_URL + "/get");
        java.net.http.HttpRequest allRequest = java.net.http.HttpRequest.newBuilder().uri(java.net.URI.create(BASE_URL + "/get")).GET().build();
        httpClient.sendAsync(allRequest, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
            .thenApply(java.net.http.HttpResponse::body)
            .thenAccept(json -> {
                try {
                    System.out.println("后端返回原始数据: " + json);
                    com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                    com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                    java.util.List<com.study.javaFx.model.Usage> usages = objectMapper.readValue(dataNode.traverse(), new com.fasterxml.jackson.core.type.TypeReference<java.util.List<com.study.javaFx.model.Usage>>(){});
                    javafx.collections.ObservableList<com.study.javaFx.model.Usage> data = javafx.collections.FXCollections.observableArrayList(usages);
                    javafx.application.Platform.runLater(() -> table.setItems(data));
                } catch (Exception ex) {
                    System.out.println("JSON解析异常: " + ex.getMessage());
                    javafx.application.Platform.runLater(() -> showAlert("初始化数据失败: " + ex.getMessage(), false));
                }
            })
            .exceptionally(ex -> { javafx.application.Platform.runLater(() -> showAlert("初始化请求失败: " + ex.getMessage(), false)); return null; });

        // 查询按钮事件
        queryBtn.setOnAction(e -> {
            String idText = idField.getText().trim();
            if (idText.isEmpty()) {
                showAlert("请输入要查询的记录ID");
                return;
            }
            System.out.println("请求单个上机记录，id参数: " + idText);
            String url = BASE_URL + "/get/" + idText;
            java.net.http.HttpRequest request = java.net.http.HttpRequest.newBuilder().uri(java.net.URI.create(url)).GET().build();
            httpClient.sendAsync(request, java.net.http.HttpResponse.BodyHandlers.ofString(java.nio.charset.StandardCharsets.UTF_8))
                .thenApply(java.net.http.HttpResponse::body)
                .thenAccept(json -> {
                    try {
                        System.out.println("后端返回原始数据: " + json);
                        com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(json);
                        com.fasterxml.jackson.databind.JsonNode dataNode = node.get("data");
                        com.study.javaFx.model.Usage usage = objectMapper.readValue(dataNode.traverse(), com.study.javaFx.model.Usage.class);
                        java.util.List<com.study.javaFx.model.Usage> usages = new java.util.ArrayList<>();
                        if (usage != null) usages.add(usage);
                        javafx.collections.ObservableList<com.study.javaFx.model.Usage> data = javafx.collections.FXCollections.observableArrayList(usages);
                        javafx.application.Platform.runLater(() -> table.setItems(data));
                    } catch (Exception ex) {
                        System.out.println("JSON解析异常: " + ex.getMessage());
                        javafx.application.Platform.runLater(() -> showAlert("解析数据失败: " + ex.getMessage(), false));
                    }
                })
                .exceptionally(ex -> { javafx.application.Platform.runLater(() -> showAlert("请求失败: " + ex.getMessage(), false)); return null; });
        });

        VBox vbox = new VBox(queryPane, table);
        vbox.setPadding(new Insets(10));
        Scene scene = new Scene(vbox, 900, 400);
        dialog.setScene(scene);
        dialog.showAndWait();
    }

    /**
     * 显示错误弹窗
     */
    private void showAlert(String msg, boolean success) {
        javafx.application.Platform.runLater(() -> {
            Alert.AlertType type = success ? Alert.AlertType.INFORMATION : Alert.AlertType.ERROR;
            new Alert(type, msg).showAndWait();
        });
    }

    // 信息弹窗快捷方法
    private void showAlert(String msg) {
        showAlert(msg, true);
    }

    /**
     * 显示标准信息弹窗
     * @param msg 提示信息
     */
    private void showInfoDialog(String msg) {
        javafx.application.Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("消息");
            alert.setHeaderText(null);
            alert.setContentText(msg);
            alert.showAndWait();
        });
    }
} 